package org.sith.taskrunner.ejb.services.impl;

import org.sith.taskrunner.api.exceptions.TaskExecutionException;
import org.sith.taskrunner.api.exceptions.TaskInitException;
import org.sith.taskrunner.api.exceptions.TransformInputDataException;
import org.sith.taskrunner.api.task.Task;
import org.sith.taskrunner.api.task.TaskExecutionResult;
import org.sith.taskrunner.api.task.TaskInputData;
import org.sith.taskrunner.api.toolkit.TaskToolkit;
import org.sith.taskrunner.ejb.exceptions.EJBServiceExecutionException;
import org.sith.taskrunner.ejb.interceptors.PermissionsChecker;
import org.sith.taskrunner.ejb.services.TaskToolkitRegisterService;
import org.sith.taskrunner.ejb.services.WebTaskExecutorService;
import org.sith.taskrunner.ejb.transformers.StringResult;

import javax.ejb.EJB;
import javax.ejb.Stateful;
import javax.interceptor.Interceptors;
import java.io.Serializable;

@Interceptors(PermissionsChecker.class)
@Stateful(name = "WebTaskExecutorServiceEJB")
public class WebTaskExecutorServiceBean implements WebTaskExecutorService, Serializable {

    @EJB(name = "TaskToolkitRegisterServiceEJB")
    private TaskToolkitRegisterService toolkitRegisterServiceEJB;


    public WebTaskExecutorServiceBean() {
    }


    @Override
    public StringResult makeTask(TaskToolkit toolkit, Object data) throws EJBServiceExecutionException {
        try {
            TaskInputData inputData = toolkit.getInputDataTransofrmer().transform(data);
            Task task = toolkit.createTaskInstance();
            task.init(inputData);
            TaskExecutionResult result = task.executeTask();
            StringResult transformedResult = new StringResult();
            toolkit.getResultTransformer().transform(result, transformedResult);
            return transformedResult;
        } catch (TaskExecutionException e) {
            throw new EJBServiceExecutionException(e);
        } catch (TransformInputDataException e) {
            throw new EJBServiceExecutionException(e);
        } catch (TaskInitException e) {
           throw new EJBServiceExecutionException(e);
        }


    }






}
